<!-- 修改密码 -->
<template>
  <div class="changePwd-container">
    <BackgroundBox>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        style="width: 500px"
        label-width="auto"
      >
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="ruleForm.oldPwd" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="ruleForm.newPwd" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input v-model="ruleForm.confirmPwd" show-password />
        </el-form-item>
        <el-form-item>
          <el-button :disabled="isDisRef" type="primary" @click="submitForm(ruleFormRef)">
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </BackgroundBox>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { updataLoginPwd } from "@/api/user.js";
import {useUserStore} from "@/store/useUserStore.js";
import BackgroundBox from "@/components/BackgroundBox/index.vue";
const {Logout} = useUserStore();
const ruleFormRef = ref();
const isDisRef = ref(false);
const ruleForm = reactive({
  oldPwd: "",
  newPwd: "",
  confirmPwd: "",
});
const validateOldAndNew = (rule, value, callback) => {
  if (ruleForm.oldPwd === ruleForm.newPwd) {
    callback("新密码不能和旧密码一致");
    return;
  }
  callback();
};
const validateNewAndConfirm = (rule, value, callback) => {
  if (ruleForm.newPwd !== ruleForm.confirmPwd) {
    callback("新密码和重新输入的密码不一致");
    return;
  }
  callback();
};
const rules = reactive({
  oldPwd: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  newPwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 10, message: "6-10位的密码", trigger: "blur" },
    { validator: validateOldAndNew, trigger: "blur" },
  ],
  confirmPwd: [
    { required: true, message: "请重新输入密码", trigger: "blur" },
    { min: 6, max: 10, message: "6-10位的密码", trigger: "blur" },
    { validator: validateNewAndConfirm, trigger: "blur" },
  ],
});

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      isDisRef.value = true
      const { data } = await updataLoginPwd({ ...ruleForm });
      if (data.state === 2) {
        ElMessage.error("旧密码不正确");
      } else if (data.state === 1) {
        ElMessage({
          message: "修改成功",
          type: "success",
        });
        formEl.resetFields();
        Logout();
      }
    }
    isDisRef.value = false
  });
};
</script>

<style lang="less" scoped>
.changePwd-container {
  width: 100%;

  margin: 20px 0;
  .back-container {
    padding: 20px;
  }
}
</style>